<template>
	<div class="container">
		<!-- ref是给表单添加一个引用名称，可以直接访问被标记的元素 -->
		<el-form ref="loginForm" :model="FormData" hide-required-asterisk :rules="formRules" label-width="65px">
			<h2>胖虎到家 - 后台登录</h2>
			<el-form-item label="账号" prop="username">
				<el-input suffix-icon="el-icon-user" placeholder="请输入账号" v-model="FormData.username"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input suffix-icon="el-icon-lock" placeholder="请输入密码" type="password"
					v-model="FormData.password"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="login" :keyup="13">登录</el-button>
				<el-button @click="formReset">取消</el-button>
			</el-form-item>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				FormData: {
					username: 'admin',
					password: 'admin'
				},
				formRules: {
					username: [{ //验证账号规则
							required: true, //是否必填
							message: '请输入账号', //验证不通过时的提示信息
							trigger: 'blur' //触发验证的时机，如 “blur” 表示失去焦点时触发验证
						},
						{
							min: 2,
							max: 20,
							message: '账号长度在2到20字符之间',
							trigger: 'blur'
						}
					],
					password: [{ //验证密码规则
							required: true, //是否必填
							message: '请输入密码', //验证不通过时的提示信息
							trigger: 'blur' //触发验证的时机，如 “blur” 表示失去焦点时触发验证
						},
						{
							min: 2,
							message: '密码长度至少为2个字符',
							trigger: 'blur'
						}
					]
				}
			}

		},
		methods: {
			login() {
				this.$refs.loginForm.validate(valid => { //  验证数据   valid 返回值boolean类型，
					if (valid) {
						//数据合法后，调用后端接口，实现登录效果
						this.$http.post('http://43.143.190.87:8182/login?username=' + this.FormData.username +
								'&pwd=' + this.FormData.password)
							.then(res => {
								if (res.data.code == 1) {
									//1.将登录成功的用户信息存储在sessionStorage中
									// sessionStorage.setItem('userInfo', this.FormData.username)
									// sessionStorage.setItem('userInfo', res.data.data.pwd)
									//2.跳转到主页面
									this.$router.push('/main')
									this.$message.success('登录成功！')
								} else {
									this.$message.error('账号或密码错误！')
								}
							})
							.catch(error => {
								this.$message.error('服务器异常！')
							})
					} else {
						this.$message.error('账号或密码不合法！')
					}
				})
			},
			formReset() {
				// this.$refs['loginForm'].resetFields();
				this.$refs.loginForm.resetFields();
			}
		}
	}
</script>

<style scoped>
	.container {
		height: 100vh;
		background: url('../assets/login_bg.jpg') no-repeat center;
		background-size: 100% 100%;
		overflow: hidden;
	}

	.el-form {
		width: 450px;
		margin: 150px auto;
		padding: 30px 50px;
		border-radius: 10px;
		box-shadow: 0 8px 16px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
		background: rgba(255, 255, 255, 0.8);

	}

	h2 {
		text-align: center;
	}
</style>